package com.byzk.p2p.admin.base.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.joda.time.DateTime;

/**
 *时间工具类 
 */
public class DateUtils {

    public final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public final static String FULL_DATE_FORMAT="yyyyMMddHHmmss";

    public final static String DATE_FORMAT="yyyyMMdd";
    
    public final static String YEAR_MOUTH_DAY_FORMAT = "yyyy-MM-dd";
    
    public final static String YEAR_MOUTH_FORMAT = "yyyy-MM";
    
	public final static DateFormat YYYYMMDDMMHHSSSSS = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	
	public final static DateFormat YYYYMMDDHHMMSS = new SimpleDateFormat("yyyyMMddHHmmss");
	
	public final static String HHMMSS = "HHmmss";

    public final static String UTIL_MAONTH="month";
    
    public final static String UTIL_DAY="day";
   
    /*** 
    * <p>Description: 获取前月的第一天</p>
    * <p>Company: xbd</p> 
    * @author fdq
    * @date 2016年9月13日
    */
    public static Date getFirstDayOfMonth() { 
    	Calendar c = Calendar.getInstance();    
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        return c.getTime();
    }

    /*** 
    * <p>Description: 获取前月的最后一天</p>
    * <p>Company: xbd</p> 
    * @author fdq
    * @date 2016年9月13日
    */
    public static Date getLastDayOfMonth() { 
    	Calendar ca = Calendar.getInstance();    
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));  
        return ca.getTime();
    }
    
    /**
     * 获取当前系统时间的字符串 - yyyy-MM-dd HH:mm:ss
     * @return
     */
    
    public static String getNowTimeString() {
        return new DateTime().toString(DEFAULT_DATE_FORMAT);
    }

    /**
     * 获取 N 天以前的 0:0:0 000 （凌晨）
     * @param day
     * @return
     */
    public static Date getFirstSecondFewDaysAgo(int day){
        DateTime dt = new DateTime();
        dt = dt.minusDays(day);
        dt = dt.withTime(0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date getFirstSecondFewsAfter(int count,String code){
        DateTime dt = new DateTime();
        if(code.equals("day")){
            dt = dt.plusDays(count+1);
        }else{
            dt=dt.plusMonths(count+1);
        }
        dt = dt.withTime(0, 0, 0, 0);
        return dt.toDate();
    }


    /**
     * 获取N天后的 23:59:59 999（凌晨）
     * @param day
     * @return
     */
    public static Date getFirstSecondFewDaysAfter(int day){
        DateTime dt =new DateTime();
        dt = dt.plusDays(day);
        dt = dt.withTime(23,59, 59, 999);
        return dt.toDate();
    }

    /**
     * 获取明天凌晨00:00:00
     */
    public static Date getTomorrow(){
        DateTime dt = new DateTime();
        dt = dt.plusDays(1);
        dt = dt.withTime(0, 0, 0, 0);
        return dt.toDate();
    }


    /**
     * 获取 N 天以前的 23:59:59 999 （午夜）
     * @param day
     * @return
     */
    public static Date getLastSecondFewDaysAgo(int day){
        DateTime dt = new DateTime();
        dt = dt.minusDays(day);
        dt = dt.withTime(23, 59, 59, 999);
        return dt.toDate();
    }

    /**
     * 获取指定的某一天的 0:0:0 000 （凌晨）
     * @param date
     * @return
     */
    public static Date getFirstSecondOfTheDay(Date date){
        DateTime dt = new DateTime(date);
        dt = dt.withTime(0, 0, 0, 0);
        return dt.toDate();
    }
    /**
     * 获取指定的某一天的 23:59:59 999 （午夜）
     * @param date
     * @return
     */
    public static Date getLastSecondOfTheDay(Date date){
        DateTime dt = new DateTime(date);
        dt = dt.withTime(23, 59, 59, 999);
        return dt.toDate();
    }

    /***
     * 格式化时间 - yyyy-MM-dd
     * @param date
     * @return
     */
    public static String formatTime(Date date){
        return new DateTime(date).toString(YEAR_MOUTH_DAY_FORMAT);
    }
    
    public static String formatYearMonth(Date date){
        return new DateTime(date).toString(YEAR_MOUTH_FORMAT);
    }    
    /***
     * 格式化时间
     * @param date
     * @return
     */
    /***
     * 格式化时间 - yyyy-MM-dd HH:mm:ss
     * @param dateLong
     * @return
     */
    public static String formatFullTime(Date dateLong){
        return new DateTime(dateLong).toString(DEFAULT_DATE_FORMAT);
    }

    /**
     * 获取今天的 23:59:59 999 （午夜）
     * @return
     */
    public static Date getLastSecondOfToday() {
        return getLastSecondFewDaysAgo(0);
    }
    /**
     * 获取今天的 0:0:0 000 （凌晨）
     * @return
     */
    public static Date getFirstSecondOfToday() {
        return getFirstSecondFewDaysAgo(0);
    }
    /**
     * 获取昨天的 23:59:59 999 （午夜）
     * @return
     */
    public static Date getLastSecondOfYestoday() {
        return getLastSecondFewDaysAgo(1);
    }
    /**
     * 获取今天的 0:0:0 000（凌晨）
     * @return
     */
    public static Date getFirstSecondOfYestoday() {
        return getFirstSecondFewDaysAgo(1);
    }

    /**
     * 转换字符串类型时间为 Date 对象。
     *
     * @param dateString
     * @param format
     * @return
     * @throws java.text.ParseException
     */
    public static Date convert(String dateString, String format) throws ParseException {
        return new SimpleDateFormat(format).parse(dateString);
    }

    /**
     * 得到几天后的时间
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDayAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }

    /**
     * 得到几月后的时间
     *
     * @param d
     * @param month
     * @return
     */
    public static Date getMonthAfter(Date d, int month) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.add(Calendar.MONTH,month);
        return now.getTime();
    }
    
    public static String getFullFormat(){
        return new DateTime().toString(FULL_DATE_FORMAT);
    }

    
    public static String getHHmmssFormat(){
        return new DateTime().toString(HHMMSS);
    }
    
    /*** 
     * 日期减N天、加N天 
     *  
     * @param option 
     *            传入类型 pre：- ，next：+ 
     * @param _date 
     *            2014-11-24 
     * @param day 
     *            天数
     * @return  
     */  
    public static String checkOption(String option, Date date,int day) {  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cl = Calendar.getInstance();  
        cl.setTime(date);  
        if ("pre".equals(option)) {  
            // 时间减一天  
            cl.add(Calendar.DAY_OF_YEAR, -day);  
  
        } else if ("next".equals(option)) {  
            // 时间加一天  
            cl.add(Calendar.DAY_OF_YEAR, day);  
        } else {  
            // do nothing  
        }  
        date = cl.getTime();  
        return sdf.format(date);  
    }  
    
    public static int dateSubtraction(Date d1,Date d2){
    	long temp=d1.getTime()-d2.getTime();
    	int minute = (int)temp/60;  
    	return minute;
    }
    
    /**
     * 获取两个时间相隔天数绝对值
     * @param date1
     * @param date2
     * @return 相隔天数
     * @throws ParseException
     */
    public static int daysBetween(Date date1,Date date2) throws ParseException {    
        SimpleDateFormat sdf=new SimpleDateFormat(YEAR_MOUTH_DAY_FORMAT);  
        date1=sdf.parse(sdf.format(date1));  
        date2=sdf.parse(sdf.format(date2));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(date1);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();         
        long between_days=Math.abs((time2-time1)/(1000*3600*24));
        return Integer.parseInt(String.valueOf(between_days));           
    }
    
    /**
     * 获取两个时间相隔天数
     * <br>注：（不含绝对值）
     * @param date1
     * @param date2
     * @return 相隔天数
     * @throws ParseException
     */
    public static int betweenDays(Date date1,Date date2) throws ParseException {    
        SimpleDateFormat sdf=new SimpleDateFormat(YEAR_MOUTH_DAY_FORMAT);  
        date1=sdf.parse(sdf.format(date1));  
        date2=sdf.parse(sdf.format(date2));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(date1);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));           
    }
    
    /**
     * 获取两个时间相隔天数及时分秒
     * @param date1
     * @param date2
     * @return xx天xx小时xx分钟xx秒
     * @throws ParseException
     */
    public static String getDistanceTime(Date date1,Date date2) throws ParseException { 
    	long day = 0; 
        long hour = 0; 
        long min = 0; 
        long sec = 0; 
        long time1 = date1.getTime(); 
        long time2 = date2.getTime(); 
        long diff ; 
        if(time1-time2<0) { 
            diff = time2 - time1; 
        } else { 
            diff = time1 - time2; 
        } 
        day = diff / (24 * 60 * 60 * 1000); 
        hour = (diff / (60 * 60 * 1000) - day * 24); 
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); 
        sec = (diff/1000-day*24*60*60-hour*60*60-min*60); 
        return day + "天" + hour + "小时" + min + "分" + sec + "秒"; 
    } 
    
    /**
     * 获取两个时间相隔小时
     * @param date1
     * @param date2
     * @return xx小时
     * @throws ParseException
     */
    public static long getDistanceTimeHour(Date date1,Date date2) throws ParseException { 
    	long day = 0; 
        long hour = 0; 
        long time1 = date1.getTime(); 
        long time2 = date2.getTime(); 
        long diff ; 
        if(time1-time2<0) { 
            diff = time2 - time1; 
        } else { 
            diff = time1 - time2; 
        } 
        day = diff / (24 * 60 * 60 * 1000); 
        hour = (diff / (60 * 60 * 1000) - day * 24); 
        return hour; 
    }
    
    /**
     * 获取两个时间相隔分钟
     * @param date1
     * @param date2
     * @return xx分钟
     * @throws ParseException
     */
    public static long getDistanceTimeMin(Date date1,Date date2) throws ParseException { 
    	long day = 0; 
        long hour = 0; 
        long min = 0; 
        long time1 = date1.getTime(); 
        long time2 = date2.getTime(); 
        long diff ; 
        if(time1-time2<0) { 
            diff = time2 - time1; 
        } else { 
            diff = time1 - time2; 
        } 
        day = diff / (24 * 60 * 60 * 1000); 
        hour = (diff / (60 * 60 * 1000) - day * 24); 
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); 
        return min; 
    } 
    
    /**
     * 获取两个时间相隔秒数
     * @param date1
     * @param date2
     * @return xx秒
     * @throws ParseException
     */
    public static long getDistanceTimeSec(Date date1,Date date2) throws ParseException { 
        long time1 = date1.getTime(); 
        long time2 = date2.getTime(); 
       
        return time2-time1; 
    }
    
    public static long getDistanceTimeNum(Date date1,Date date2) throws ParseException { 
        long time1 = date1.getTime(); 
        long time2 = date2.getTime(); 
        return time1-time2;
    } 
    
   /**
    * 根据用户生日计算年龄
    * @param birthday 生日
    * @return
    */
    public static int getAgeByBirthday(Date birthday) throws IllegalArgumentException{
    	Calendar cal = Calendar.getInstance();
    	if (cal.before(birthday)) {
    		throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
    	}
    	int yearNow = cal.get(Calendar.YEAR);
    	int monthNow = cal.get(Calendar.MONTH) + 1;
    	int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
    	cal.setTime(birthday);
    	int yearBirth = cal.get(Calendar.YEAR);
    	int monthBirth = cal.get(Calendar.MONTH) + 1;
    	int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
    	int age = yearNow - yearBirth;
    	if (monthNow <= monthBirth) {
    		if (monthNow == monthBirth) {
    			if (dayOfMonthNow < dayOfMonthBirth) {
    				age--;
    			}
    		} else {
    			age--;
    		}
    	}
    	return age;
    }
    
    /**
	 * 仅保留日期，其它的清0， 如2010-7-27 00:00:00.000
	 * 
	 * @param date
	 * @return
	 */
	public static Date getRealDate(Date date) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(date.getTime());
		gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
		gc.set(GregorianCalendar.MINUTE, 0);
		gc.set(GregorianCalendar.SECOND, 0);
		gc.set(GregorianCalendar.MILLISECOND, 0);
		return new Date(gc.getTimeInMillis());
	}

	/**
	 * 获取日期所在当前的最大值 ，如2010-7-27 23:59:59.000
	 * 
	 * @param date
	 * @return
	 */
	public static Date getFullDate(Date date) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTimeInMillis(date.getTime());
		gc.set(GregorianCalendar.HOUR_OF_DAY, 23);
		gc.set(GregorianCalendar.MINUTE, 59);
		gc.set(GregorianCalendar.SECOND, 59);
		gc.set(GregorianCalendar.MILLISECOND, 0);
		return new Date(gc.getTimeInMillis());
	}
	
	
	public static String getNextMonth(){
		Calendar cal = Calendar.getInstance();
    	int year = cal.get(Calendar.YEAR);
    	int month = cal.get(Calendar.MONTH) + 1;
    	if(month==12){
    		return (year+1)+"-01";
    	}else{
    		month=month+1;
    		if(month<10){
    			return year+"-0"+month;
    		}else{
    			return year+"-"+month;
    		}
    	}
	}
	
	/**
	 * 将秒变成字符串--倒计时用
	 * @param second 秒
	 * @return
	 */
	public static String formatSecond(int second) {
		if(second < 0) {
			return "00:00:00";
		}
		int hour;//小时
		int nimute;//分钟
		String hourStr = "";
		String nimuteStr = "";
		String secondStr = "";
		if(second > 3600) {
			hour = second / 3600;
			second = second % 3600;
			if(second == 0) {//整除
				hourStr = hour < 10 ? "0" + hour : hour+"";
				return hourStr+":00:00";
			}else {
				nimute = second / 60;
				second = second % 60;
				if(second == 0) {//整除
					hourStr = hour < 10 ? "0" + hour : hour+"";
					nimuteStr = nimute < 10 ? "0" + nimute : nimute+"";
					return hourStr+":" + nimuteStr + ":00";
				} else {
					hourStr = hour < 10 ? "0" + hour : hour+"";
					nimuteStr = nimute < 10 ? "0" + nimute : nimute+"";
					secondStr = second < 10 ? "0" + second : second + "";
					return hourStr+":" + nimuteStr + ":"+ secondStr;
				}
			}
		}else {
			nimute = second / 60;
			second = second % 60;
			if(second == 0) {//整除
				nimuteStr = nimute < 10 ? "0" + nimute : nimute+"";
				return "00:" + nimuteStr + ":00";
			} else {
				nimuteStr = nimute < 10 ? "0" + nimute : nimute+"";
				secondStr = second < 10 ? "0" + second : second + "";
				return "00:" + nimuteStr + ":"+ secondStr;
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = sdf.parse("2016-08-23 16:00:00");
		int second = (int) ((time.getTime() - new Date().getTime())/1000L);
		System.out.println(formatSecond(second));
	}
	
	
	/**
	 * 
	* <p>Description: 格式化时间为yyyyMMdd</p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年10月14日上午10:10:53
	 */
	public  static  String FormatDate(){
		 return new DateTime().toString(DATE_FORMAT);
	}
    /*public static void main(String[] args) throws ParseException{
    	Date date1= DateUtils.getMonthAfter(new Date(), 3);
    	System.out.println(DateUtils.getRealDate(date1));
    	Date date2 = new Date();
    	System.out.println(date2);
    	
    	//满标复审时间
		String checkTime = DateUtils.formatTime(date1);
		//转让时间
		String changeTime = DateUtils.formatTime(new Date());
		
		System.out.println((new Date().getTime()-date1.getTime())/(24*60*60*1000));
    }*/
}

